﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>屏幕共享示例</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            font-family: Arial, sans-serif;
        }
        video {
            margin-top: 20px;
            width: 80%;
            max-width: 800px;
            border: 2px solid #333;
            background-color: #000;
        }
    </style>
</head>
<body>
<h1>屏幕共享示例</h1>
<button id="startButton">开始屏幕共享</button>
<button id="stopButton" disabled>停止屏幕共享</button>
<video id="screenVideo" autoplay playsinline></video>

<script>
    const startButton = document.getElementById('startButton');
    const stopButton = document.getElementById('stopButton');
    const videoElement = document.getElementById('screenVideo');

    let screenStream;

    // 开始屏幕共享
    startButton.addEventListener('click', async () => {
        try {
            // 获取屏幕共享流
            screenStream = await navigator.mediaDevices.getDisplayMedia({
                video: true,
                audio: false
            });

            // 将流传递给video元素播放
            videoElement.srcObject = screenStream;
            startButton.disabled = true;
            stopButton.disabled = false;

            // 监听流结束事件
            screenStream.getVideoTracks()[0].addEventListener('ended', () => {
                stopScreenShare();
            });
        } catch (error) {
            console.error("屏幕共享失败:", error);
        }
    });

    // 停止屏幕共享
    stopButton.addEventListener('click', stopScreenShare);

    function stopScreenShare() {
        if (screenStream) {
            const tracks = screenStream.getTracks();
            tracks.forEach(track => track.stop()); // 停止所有轨道
            videoElement.srcObject = null; // 清除视频元素源
            startButton.disabled = false;
            stopButton.disabled = true;
        }
    }
</script>
</body>
</html>